//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package event_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type EventStageDbItem struct {
	EventStageId      string `bson:"_id"`
	ProjectId         string `bson:"projectId"`
	EventSourceId     string `bson:"eventSourceId"`
	SourceUserName    string `bson:"sourceUserName"`
	SourceDisplayName string `bson:"sourceDisplayName"`
	EventType         uint32 `bson:"eventType"`
	EventData         []byte `bson:"eventData"`
	EventTime         int64  `bson:"eventTime"`
}

type _EventStageDao struct {
	mc *mongo.Collection
}

func newEventStageDao(db *mongo.Database) (*_EventStageDao, error) {
	mc := db.Collection(db_ns.DB_NS_EVENT + "stage")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}, {"eventSourceId", 1}, {"sourceUserName", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_EventStageDao{mc: mc}, nil
}

func (db *_EventStageDao) RemoveByEventSource(ctx context.Context, projectId, eventSourceId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"projectId": projectId, "eventSourceId": eventSourceId})
	return err
}

func (db *_EventStageDao) Insert(ctx context.Context, dbItem *EventStageDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_EventStageDao) ListBySourceUser(ctx context.Context, projectId, eventSourceId, sourceUserName string) ([]*EventStageDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "eventSourceId": eventSourceId, "sourceUserName": sourceUserName})
	if err != nil {
		return nil, err
	}
	retList := []*EventStageDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_EventStageDao) Remove(ctx context.Context, eventStageId, projectId, eventSourceId, sourceUserName string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": eventStageId, "projectId": projectId, "eventSourceId": eventSourceId, "sourceUserName": sourceUserName})
	return err
}
